import { useEffect, useState, useRef, useMemo } from 'react';
import { Carousel, Image } from 'antd';
import loadable from '@loadable/component';

import useDevice, { DEVICES } from '@/hooks/useDevice';
import styles from './index.module.scss';

const IconFont = loadable(() => import('@/components/IconFont'));
const Gallery = loadable(() => import('./../Gallery'));

export default props => {
    const { images = [], index=0, primaryIndex } = props;
    // 优先使用 primaryIndex，如果没有则使用 index
    const defaultIndex = primaryIndex !== undefined ? primaryIndex : index;
    const initState = () => ({
        activeIndex: defaultIndex,
        galleryVisible: false,
    });
    const [state, setState] = useState(initState);
    const carouselRef = useRef(null);
    const isMobile = useDevice() === DEVICES.MOBILE;

    const list = useMemo(() => {
        if (!Array.isArray(images)) return [];
        return images.filter(Boolean);
    }, [images]);

    const toIndex = (idx) => {
        setState(o => ({ ...o, activeIndex: idx }));
        carouselRef.current?.goTo(idx, true);
    };

    const showGallery = () => {
        // 仅在移动端展示画廊
        if (!isMobile) return;
        setState(o => ({...o, galleryVisible: true}));
    };

    // 当 defaultIndex 或图片列表变化时更新状态和轮播图位置
    useEffect(() => {
        setState(o => ({ ...o, activeIndex: defaultIndex }));
        // 确保轮播图也跳转到正确的位置
        if (carouselRef.current && list.length > 0) {
            let t = setTimeout(() => {
                clearTimeout(t);
                carouselRef.current?.goTo(defaultIndex, false);
            }, 0);
        }
    }, [defaultIndex, list.length]);

    return (
        <>
            <div className={styles['container']}>
                {
                    !!list.length && <div className={styles['viewer']}>
                        <div className={styles['pagination']} onClick={showGallery}>
                            { isMobile && <span><IconFont name="icon-app" /></span> }
                            {state.activeIndex+1}/{list.length}
                        </div>

                        <Carousel
                            ref={carouselRef}
                            arrows={true}
                            draggable={true}
                            dots={false}
                            beforeChange={(from, to) => setState(o => ({ ...o, activeIndex: to }))}
                        >
                            {list.map((src, i) => (
                                <div key={i} className={styles['slide']}>
                                    {
                                        state.activeIndex === i ? (
                                            <Image.PreviewGroup items={list}>
                                                <Image
                                                    src={`${src}?x-oss-process=image/resize,w_1080/quality,q_85`}
                                                    placeholder={
                                                        <img
                                                            src={`${src}?x-oss-process=image/resize,w_64/quality,q_30`}
                                                            decoding="async"
                                                        />
                                                    }
                                                />
                                            </Image.PreviewGroup>
                                        ) : (
                                            <div />
                                        )
                                    }
                                </div>
                            ))}
                        </Carousel>
                    </div>
                }

                <div className={styles['thumbs']}>
                    {
                        list.length === 0 ?
                            <div className={styles['thumb-placeholder']}>暂无图片</div>
                            :
                            !isMobile &&
                                list.map((src, i) => (
                                    <div
                                        key={i}
                                        className={`${styles['thumb']} ${state.activeIndex === i ? styles['active'] : ''}`}
                                        onClick={() => toIndex(i)}
                                    >
                                        <img src={`${src}?x-oss-process=image/resize,p_10`} alt={`thumb-${i}`} />
                                    </div>
                                ))
                    }
                </div>
            </div>

            {/* 画册 */}
            <Gallery
                items={list}
                open={state.galleryVisible}
                onOpenChange={(open) => setState(o => ({...o, galleryVisible: !!open}))}
            />
        </>
    );
};
